#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author:zhangcong
# Email:zc_92@sina.com


from django.shortcuts import render
from webadmin.views_dir import pub

from django.http import JsonResponse

from datetime import datetime

from webadmin.views_dir.mongo_oper import get_db_obj
from bson.objectid import ObjectId


# 用户管理
@pub.is_login
def user_management(request):

    if "pageNum" in request.POST:
        pageNum = int(request.POST.get("pageNum"))
    else:
        pageNum = 1

    if "numPerPage" in request.POST:
        numPerPage = int(request.POST.get("numPerPage"))
    else:
        numPerPage = 20

    user_objs_all = get_db_obj().user.find()
    count = user_objs_all.count()   # 用户的总数
    user_objs = user_objs_all.skip(pageNum * numPerPage - numPerPage).limit(numPerPage)

    # 所有角色的信息
    roles_data = {}
    for i in get_db_obj().roles.find({}, {"_id": 1, "name": 1}):
        roles_data[i["_id"]] = i["name"]

    # 所有用户的信息
    user_data = {}
    for i in get_db_obj().user.find({}, {"_id": 1, "username": 1}):
        user_data[i["_id"]] = i["username"]

    return render(request, 'webadmin/user/user_management.html', locals())


@pub.is_login
def user_management_oper(request, oper_type, o_id):

    user_id = request.session['user_id']
    response = pub.BaseResponse()

    if request.method == "POST":
        # 添加
        if oper_type == "add":
            print(request.POST)

            username = request.POST.get('username')
            password = request.POST.get('password')
            role_id = request.POST.get('role_id')

            if not response.statusCode and not username.strip():
                response.statusCode = 300
                response.message = "用户名称不能为空"

            if not response.statusCode and not password.strip():
                response.statusCode = 300
                response.message = "登录密码不能为空"

            if not response.statusCode and not role_id.strip():
                response.statusCode = 300
                response.message = "请选择用户对应角色"

            if not response.statusCode:
                user_obj = get_db_obj().user.find_one({"username": username})
                if user_obj:
                    response.statusCode = 300
                    response.message = "用户名已经存在"

            if not response.statusCode:

                get_db_obj().user.insert({
                    "_id": str(ObjectId()),
                    "username": username,
                    "password": pub.str_encrypt(password),
                    "role_id": role_id,
                    "create_date": datetime.now(),
                    "status": "1",
                    "create_user_id": user_id,
                })

                response.statusCode = 200
                response.message = "添加成功"

        # 修改
        elif oper_type == "update":

            username = request.POST.get('username')
            role_id = request.POST.get('role_id')
            status = request.POST.get('status')

            if not response.statusCode and not username.strip():
                response.statusCode = 300
                response.message = "用户名称不能为空"

            if not response.statusCode and not role_id.strip():
                response.statusCode = 300
                response.message = "请选择用户对应角色"

            if not response.statusCode:
                user_obj = get_db_obj().user.find_one({"username": username, "_id": {"$ne": o_id}})
                if user_obj:
                    response.statusCode = 300
                    response.message = "用户名已经存在"

            if not response.statusCode:
                get_db_obj().user.update({"_id": o_id}, {"$set": {
                    "username": username,
                    "role_id": role_id,
                    "status": status,
                }})

                response.statusCode = 200
                response.message = "修改成功"

        # 删除
        elif oper_type == "del":
            # 判断该用户下是否有文章
            article_obj = get_db_obj().articles.find_one({"user_id": o_id})
            if article_obj:
                response.statusCode = 300
                response.message = "删除失败,该用户下存在文章,请联系管理员将文章转移后在进行该操作"
                response.callbackType = None
            else:
                get_db_obj().user.remove({"_id": o_id})

                response.statusCode = 200
                response.message = "删除成功"
                response.callbackType = None

        return JsonResponse(response.__dict__)

    else:
        # 添加
        if oper_type == "add":

            roles_list = get_db_obj().roles.find({}, {"name": 1, "_id": 1})

            return render(request, 'webadmin/user/user_management_modal_add.html', locals())

        # 修改
        elif oper_type == "update":
            roles_list = get_db_obj().roles.find({}, {"name": 1, "_id": 1})
            user_obj = get_db_obj().user.find_one({"_id": o_id})

            return render(request, 'webadmin/user/user_management_modal_update.html', locals())
